package com.cloudcc.mobile.view.main.fragment;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import butterknife.Bind;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.bus.MenuToggleEvent;
import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.RequestListener;
import com.cloudcc.cloudframe.ui.viewgroup.loadmore.LoadMoreContainer;
import com.cloudcc.cloudframe.ui.viewgroup.loadmore.LoadMoreHandler;
import com.cloudcc.cloudframe.ui.viewgroup.loadmore.LoadMoreListViewContainer;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrDefaultHandler;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrFrameLayout;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrHandler;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.header.DefaultMaterialHeader;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.header.MaterialHeader;
import com.cloudcc.cloudframe.util.DensityUtils;
import com.cloudcc.cloudframe.util.ListUtils;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.CoworkerListAdapter;
import com.cloudcc.mobile.adapter.CoworkerListAdapter.OnItemFnClickListener;
import com.cloudcc.mobile.entity.CoworkerEntity;
import com.cloudcc.mobile.entity.OperateFollowRelation;
import com.cloudcc.mobile.event.CoworkerEventList.CoworkerListEvent;
import com.cloudcc.mobile.im.ui.GroupsActivity;
import com.cloudcc.mobile.manager.ContactsManager;
import com.cloudcc.mobile.presenter.ContactsPresenter;
import com.cloudcc.mobile.presenter.OtherPresenter;
import com.cloudcc.mobile.util.CharacterParser;
import com.cloudcc.mobile.util.ViewUtils;
import com.cloudcc.mobile.view.activity.UserInfoActivity;
import com.cloudcc.mobile.weight.ClearEditText;
import com.cloudcc.mobile.weight.EmptyLayout;
import com.cloudcc.mobile.widget.CloudCCTitleBar;
import com.cloudcc.mobile.widget.CloudCCTitleBar.OnTitleBarClickListener;

/** 
* @Description: 同事联系人列表
* @author wangzhiqiang
* @date 2015-12-16 下午2:50:43 
*  
*/
public class CoworkerListFragment extends BaseListFragment implements PtrHandler, LoadMoreHandler,IEventLife, OnItemFnClickListener, OnItemClickListener, OnTitleBarClickListener {

	@Bind(R.id.listview)
	protected ListView mListView;
	@Bind(R.id.load_more_list_view_ptr_frame)
	protected PtrFrameLayout mRefreshLayout;
	@Bind(R.id.load_more_list_view_container)
	protected LoadMoreListViewContainer mLoadMoreLayout;
	@Bind(R.id.filter_edit)
	protected ClearEditText mClearEditText;
	
	EmptyLayout empty_loading;
	@Bind(R.id.headerbar)
	protected CloudCCTitleBar headerbar;
	
	protected ContactsPresenter mContactPresenter =new ContactsPresenter();
	protected CoworkerListAdapter mAdapter;
	protected List<CoworkerEntity> mContactes =new ArrayList<CoworkerEntity>();
	protected CharacterParser characterParser;
	@Override
	public void init() {
		super.init();
		initHeader();
		initRefresh();
		initLoadMore();
		initRequestData();
		initFilter();
	}

	private void initHeader() {
		headerbar.setOnTitleBarClickListener(this);
		empty_loading = new EmptyLayout(mContext);
		empty_loading.setLayoutParams(new LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		ViewUtils.addListViewEmptyView(mContext, mListView, empty_loading);
		empty_loading.empty();
		
	}
	private void initFilter() {
		characterParser = CharacterParser.getInstance();
		// 根据输入框输入值的改变来过滤搜索
		mClearEditText.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start,
					int before, int count) {
				// 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
				filterData(s.toString());
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start,
					int count, int after) {
			}
			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		
	}
	
	/**
	 * 根据输入框中的值来过滤数据并更新ListView
	 * 
	 * @param filterStr
	 */
	private void filterData(String filterStr) {
		List<CoworkerEntity> filterDateList = new ArrayList<CoworkerEntity>();
		if (TextUtils.isEmpty(filterStr)) {
			filterDateList.addAll(mContactes);
		} else {
			filterDateList.clear();
			for (CoworkerEntity entity : mContactes) {
				String name = entity.getName();
				if (name!=null&&(name.indexOf(filterStr.toString().toLowerCase()) != -1|| characterParser.getSelling(name).startsWith(filterStr.toString().toLowerCase()))) {
					filterDateList.add(entity);
				}
			}
		}
		if (mAdapter!=null) {
			onRequestFinish(ListUtils.isEmpty(filterDateList));
			mAdapter.changeData(filterDateList);
		}
	}


	/**
	 * 初始化刷新
	 */
	protected void initRefresh() {
		mRefreshLayout.setLoadingMinTime(1000);
		mRefreshLayout.setPtrHandler(this);

		final MaterialHeader header = new DefaultMaterialHeader(getActivity());
		int[] colors = getResources().getIntArray(R.array.google_colors);
		header.setColorSchemeColors(colors);
		header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
		header.setPadding(0, DensityUtils.dpToPixel(mContext, 10), 0,
				DensityUtils.dpToPixel(mContext, 5));
		header.setPtrFrameLayout(mRefreshLayout);
		mRefreshLayout.setHeaderView(header);
		mRefreshLayout.addPtrUIHandler(header);
	}
	
	public void onEventMainThread(CoworkerListEvent event){
		headerbar.completeProgress();
		if (event.isError()) {
			if (isFromRefresh()) {
				mRefreshLayout.refreshComplete();
				mLoadMoreLayout.loadMoreFinish(true, false);
			} else {
				mLoadMoreLayout.loadMoreError(1002, event.getMessage());
			}
			Toast.makeText(mContext, event.getMessage(), 0).show();
			return;
		}
		ContactsManager.getInstance().saveContactesToDB(event.getData());
		onRequestFinish(ListUtils.isEmpty(event.getData()));
		refreshData(event.getData());
		
	}
	protected void refreshData(List<CoworkerEntity> data){
		if (mAdapter == null) {
			mAdapter = new CoworkerListAdapter(mContext);
			mAdapter.setOnItemFnClickListener(this);
			mListView.setAdapter(mAdapter);
			mListView.setOnItemClickListener(this);
		}
		if (isFromRefresh()) {
			mContactes.clear();
			mContactes.addAll(data);
			mAdapter.changeData(data);
		} else {
			mContactes.addAll(data);
			mAdapter.addData(data);
		}
	}
	
	protected void onRequestFinish(boolean dataIsEmpty) {

		if (isFromRefresh()) {// 第一次加载 获得的数据为空
			mRefreshLayout.refreshComplete();
			mLoadMoreLayout.loadMoreFinish(dataIsEmpty, !dataIsEmpty);
		} else {
			mLoadMoreLayout.loadMoreFinish(false, !dataIsEmpty);
		}
	}
	
	/**
	 * 初始化 加载更多
	 */
	protected void initLoadMore() {
		mLoadMoreLayout.setAutoLoadMore(true);
		mLoadMoreLayout.setOffsetSize(3);
		mLoadMoreLayout.useDefaultHeader();
		mLoadMoreLayout.setLoadMoreHandler(this);
	}
	@Override
	public void onLoadMore(LoadMoreContainer loadMoreContainer) {
		currentPage++;
		requestData();
	}
	/**
	 *  自动开启刷新请求数据
	 */
	protected void initRequestData() {
		List<CoworkerEntity> contactesFromDB = ContactsManager.getInstance().getContactesFromDB();
		if (!ListUtils.isEmpty(contactesFromDB)) {
			refreshData(contactesFromDB);
			headerbar.completeProgress();
		}
		requestData();
	}
	
	@Override
	public void requestData() {
		headerbar.beginProgress();
		mContactPresenter.getContactList(currentPage);
	}

	
	
	@Override
	public int getLayoutId() {
		return R.layout.contact_list;
	}

	@Override
	public boolean checkCanDoRefresh(PtrFrameLayout frame, View arg1, View header) {
		return PtrDefaultHandler.checkContentCanBePulledDown(frame, mListView,
				header);
	}

	@Override
	public void onRefreshBegin(PtrFrameLayout arg0) {
		onRefreshData();
	}

	@Override
	public void register() {
		EventEngine.register(this);
	}

	@Override
	public void unRegister() {
		EventEngine.uregister(this);
	}
	@Override
	public void onResume() {
		super.onResume();
		register();
	}
	@Override
	public void onStop() {
		unRegister();
		super.onStop();
	}
	OperateFollowRelation op;
	@Override
	public void onClickAtt(final int pos, CoworkerEntity t) {
		final boolean oldFollowStatus = t.isIsmefollow();
		new OtherPresenter().followPeople(t.getId(),oldFollowStatus,
				new RequestListener() {
					@Override
					public void onSuccess(Object arg0) {
						Toast.makeText(mContext, (!oldFollowStatus?"":"取消")+"关注成功~~", 0).show();
						mAdapter.getItem(pos).setIsmefollow(!oldFollowStatus);
						mAdapter.notifyDataSetChanged();
					}

					@Override
					public void onFailure(ErrorInfo arg0) {
						Toast.makeText(mContext, "操作失败~~", 0).show();
					}
				});
	}


	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
		Intent intent=new Intent(getActivity(),UserInfoActivity.class);
		intent.putExtra(UserInfoActivity.KEY_USERID, mAdapter.getItem(position).getId());
		mContext.startActivity(intent);		
	}

	@Override
	public void onClickLeft(View v) {
		EventEngine.post(new MenuToggleEvent(false, false));
	}

	@Override
	public void onClickRight(View v) {
		startActivity(new Intent(getActivity(), GroupsActivity.class));
	}
}
